import { CanActivate, ExecutionContext, Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import { Observable } from 'rxjs';
import { Permission } from 'src/modules/user/entities/Permission';
import { Request } from 'express';
import { PERMISSION_KEY } from 'src/common/decorator/permission.decorator'
import { UnLoginException, UnloginFilter } from 'src/common/exception/unlogin.filter';
interface JwtUserData {
    userId: number
    username: string
    roles: string[]
    permissions: Permission[]
}

declare module 'express' {
    interface Request {
        user: JwtUserData
    }
}

@Injectable()
export class LoginGuard implements CanActivate {
    @Inject()
    private readonly jwtService: JwtService

    @Inject()
    private readonly reflector: Reflector

    canActivate(context: ExecutionContext,): boolean | Promise<boolean> | Observable<boolean> {
        const request: Request = context.switchToHttp().getRequest()
        const requireLogin = this.reflector.getAllAndOverride(PERMISSION_KEY.login, [context.getClass(), context.getHandler()])
        if (!requireLogin) return true

        const authorization = request.headers.authorization
        if (!authorization) {
            // throw new UnauthorizedException('用户未登录')
            throw new UnLoginException()
        }
        try {
            const token = authorization.split(' ')[1]
            const data = this.jwtService.verify<JwtUserData>(token)
            request.user = data
            return true
        } catch (error) {
            throw new UnauthorizedException('token失效，请重新登录')
        }
    }
}
